package com.macaline.framemarker.plugin.pluginManager.manager;

import com.macaline.framemarker.plugin.pluginManager.PluginRegister;
import com.macaline.framemarker.plugin.pluginManager.interfacer.PluginMenuInterface;
import com.macaline.framemarker.plugin.pluginManager.util.PluginSreachUtil;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 插件管理中心
 * @author warm_joy
 */
@Component
public class PluginManager {

	public static String menuHtml = "";
	private String packageName = "";

	public PluginManager() {
		try {
			initPluginManager();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	private static void initPluginManager() throws Exception {
		menuHtml = getPluginMenu(getPluginList(), new PluginMenuGenerator());
	}

	/**
	 * 获取当前项目下插件的插件注解列表
	 * @throws ClassNotFoundException
	 */
	private static List<PluginRegister> getPluginList() throws ClassNotFoundException, UnsupportedEncodingException {
		List<PluginRegister> list = new LinkedList<PluginRegister>();
		List<Class<?>> pluginList = PluginSreachUtil.getclassInPackage("com.macaline.framemarker.plugin", true);
		Iterator<Class<?>> iterator = pluginList.iterator();
		while (iterator.hasNext()) {
			Class<?> class1 = iterator.next();
			PluginRegister annotation = class1.getAnnotation(PluginRegister.class);
			list.add(annotation);
		}
		return list;
	}

	/**
	 * 通过插件注解获取到插件功能的信息
	 * @param pluginList 扫描到的插件注解的列表
	 * @param pluginMenuGenerator 根据插件注解列表生成前端的html代码
	 */
	private static String getPluginMenu(List<PluginRegister> pluginList, PluginMenuInterface pluginMenuGenerator) {
		return pluginMenuGenerator.generateMenuHtml(pluginList);
	}

}
